package valuetypes;
import exception.DBValueException;


public class CharacterValue extends DBValue {
	private static final int CHAR_SIZE = 33;//32 characters + 1 terminator
	private static final char TERMINATOR = 'X';
	private static final char FILLER = 'O';
	
	protected int actualLength;
	protected String actualContents;
	
	public CharacterValue(){
		super(CHAR_SIZE);//32 characters + terminator;
	}
	
	public CharacterValue(byte[] data, int offset) throws DBValueException{
		super(CHAR_SIZE, data, offset);
	}

	public CharacterValue(String value) throws DBValueException {
		super(CHAR_SIZE);
		int length = value.length();
		if(length > CHAR_SIZE -1)throw DBValueException.dataSizeOutOfBounds(0, CHAR_SIZE, length);
		byte[] chardata = new byte[CHAR_SIZE];
		
		for(int i=0; i < length; i++ ){
			chardata[i] = (byte) value.charAt(i);			
		}
		chardata[length] = TERMINATOR;
		for(int i = length + 1; i < CHAR_SIZE; i++ ){
			chardata[i] = FILLER;
		}		
		this.data = chardata;
		this.actualContents = value;
		this.actualLength = length;
	}

	@Override
	public String toString(){
		return actualContents;
	}
	
	@Override
	protected void onDataChanged(byte[] oldData, byte[] newData) {
		for(int i = CHAR_SIZE-1; i >= 0; i--){
			if(newData[i] == TERMINATOR){
				actualLength = i ;
				actualContents = new String(newData, 0, actualLength);
				return;
			}
		}
	}
}
